package com.young.controller;

import com.young.pojo.MoneyExpense;
import com.young.request.MoneyExpenseRequest;
import com.young.request.AssigneeExpenseRequest;
import com.young.service.MoneyExpenseService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/expense")
public class ExpenseController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private MoneyExpenseService moneyExpenseService;

    @GetMapping("/{id}")
    public MoneyExpense getMoneyExpenseById(@PathVariable("id")String id){
        return moneyExpenseService.getMoneyExpenseById(id);
    }

    @PostMapping("/addExpense")
    public String addExpense(@RequestBody MoneyExpenseRequest moneyExpenseRequest){
        return moneyExpenseService.addMoneyExpense(moneyExpenseRequest);
    }


    @PutMapping("/approve")
    public String applyMoneyExpense(@RequestBody AssigneeExpenseRequest assigneeExpenseRequest){
        return moneyExpenseService.applyMoneyExpense(assigneeExpenseRequest);
    }

    @PutMapping("/reject")
    public String rejectMoneyExpense(@RequestBody AssigneeExpenseRequest assigneeExpenseRequest){
        return moneyExpenseService.rejectMoneyExpense(assigneeExpenseRequest);
    }

    @RequestMapping("/add")
    public String addExpense(String userId,Integer money,String description){
        HashMap<String,Object>map=new HashMap<>();
        map.put("taskUser",userId);
        map.put("money",money);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Expense", map);
        System.out.println(processInstance.getProcessDefinitionId());
        System.out.println(processInstance.getId());
        return "提交成功，流程id为："+processInstance.getId();
    }

    @RequestMapping(value = "/list")
    public Object list(String userId){
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
        for (Task task:tasks){
            System.out.println(task.getProcessInstanceId());
            System.out.println(task.toString());
        }
        return tasks.toArray().toString();
    }

    @RequestMapping(value = "/apply")
    public String apply(String taskId){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task==null){
            throw new RuntimeException("流程不存在");
        }
        HashMap<String,Object>map=new HashMap<>();
        map.put("outcome","通过");
        taskService.complete(taskId,map);
        return "processed Ok!";
    }

    @RequestMapping(value = "/reject")
    public String reject(String taskId){
        HashMap<String,Object>map=new HashMap<>();
        map.put("outcome","驳回");
        taskService.complete(taskId,map);
        return "reject";
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @GetMapping("/processDiagram")
    public void showPic(HttpServletResponse resp, @RequestParam("processId") String processId)throws Exception{
        ProcessInstance pi=runtimeService.createProcessInstanceQuery().processInstanceId(processId)
                .singleResult();
        if (pi==null){
            return;
        }
        List<Execution> executions = runtimeService.createExecutionQuery()
                .processInstanceId(processId)
                .list();
        List<String>activityIds=new ArrayList<>();
        List<String>flows=new ArrayList<>();
        for(Execution exe:executions){
            List<String>ids=runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }
        //生成流程图
        BpmnModel bpmnModel=repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf=processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator=engconf.getProcessDiagramGenerator();
        InputStream in=diagramGenerator.generateDiagram(bpmnModel,"png",activityIds,flows,engconf.getActivityFontName(),
                engconf.getLabelFontName(),engconf.getAnnotationFontName(),engconf.getClassLoader(),1.0,false);
        OutputStream out=null;
        byte[]buf=new byte[1024];
        int length=0;
        try {
            out=resp.getOutputStream();
            while ((length=in.read(buf))!=-1){
                out.write(buf,0,length);
            }
        }finally {
            if (in!=null){
                in.close();
            }
            if (out!=null){
                out.close();
            }
        }
    }
}
